package com.allwees.bs.c.module.user.repository;

import com.allwees.bs.c.module.base.repository.BaseRepository;
import com.allwees.bs.c.module.user.entity.UserCouponEntity;
import com.allwees.bs.core.model.coupon.constant.ECouponUseType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Date;
import java.util.List;

public interface UserCouponRepository extends BaseRepository<UserCouponEntity, Integer> {

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.isDeleted = 0 AND s.status = 0 AND s.overdueTime > :current")
    List<UserCouponEntity> findCanUse(@Param("userUuid") String userUuid, @Param("current") Date current);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.uuid = :uuid AND s.isDeleted = 0")
    UserCouponEntity getByUuid(@Param("uuid") String uuid);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.couponUuid = :couponUuid AND s.isDeleted = 0")
    List<UserCouponEntity> findByUserUuidAndCouponUuid(@Param("userUuid") String userUuid, @Param("couponUuid") String couponUuid);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.couponUuid = :couponUuid AND s.no = :couponNo AND s.isDeleted = 0")
    List<UserCouponEntity> findByUserUuidAndCouponUuidAndPromoCode(String userUuid, String couponUuid, String couponNo);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.no = :no AND s.isDeleted = 0")
    UserCouponEntity findByUserUuidAndNo(String userUuid, String no);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.isDeleted = 0")
    Page<UserCouponEntity> findByUserUuid(@Param("userUuid") String userUuid, Pageable pageable);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.overdueTime >= :now AND s.status = 0 AND s.isDeleted = 0")
    Page<UserCouponEntity> findAvailable(String userUuid, Date now, Pageable pageable);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.status in (1,18) AND s.isDeleted = 0")
    Page<UserCouponEntity> findUsed(String userUuid, Pageable pageable);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.couponUseType in (:useTypes)  AND s.status = 1 AND s.isDeleted = 0")
    Page<UserCouponEntity> findUsedByUseTypes(@Param("userUuid") String userUuid, @Param("useTypes") List<ECouponUseType> useTypes, Pageable pageable);

    @Query("SELECT s FROM UserCouponEntity s WHERE s.userUuid = :userUuid AND s.overdueTime < :now AND s.isDeleted = 0")
    Page<UserCouponEntity> findExpired(String userUuid, Date now, Pageable pageable);

    List<UserCouponEntity> findAllByUserUuid(String userUuid);
}
